package common

import (
	"encoding/json"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"os"
	"runtime"
	"snow-im/app/constants/common"
	"snow-im/config"
	"strconv"
	"time"
)
var ZapLogger *zap.Logger

func InitLog()  {
	base,_ :=os.Getwd()

	logpath := base+"/logs/log"
	w := getWriter(logpath)

	// 设置日志级别,debug可以打印出info,debug,warn；info级别可以打印warn，info；warn只能打印warn
	// debug->info->warn->error
	encoderConfig := zap.NewProductionEncoderConfig()
	// 时间格式
	encoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
		enc.AppendString(t.Format("2006-01-02 15:04:05"))
	}
	var core zapcore.Core
	if config.IsDebug(){
		// 开启文件及行号
		core = zapcore.NewCore(
			zapcore.NewConsoleEncoder(encoderConfig),
			zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout)),
			zap.DebugLevel,
		)
	}else{
		core = zapcore.NewCore(
			zapcore.NewConsoleEncoder(encoderConfig),
			zapcore.AddSync(w),
			zap.DebugLevel,
		)
	}

	// 开启开发模式，堆栈跟踪
	//caller := zap.AddCaller()
	// 开启文件及行号
	//development := zap.Development()
	logger := zap.New(core)
	ZapLogger = logger
}

func getWriter(filename string) io.Writer {
	// 生成rotatelogs的Logger 实际生成的文件名 demo.log.YYmmddHH
	// 保存7天内的日志，每1小时(整点)分割一次日志
	hook, err := rotatelogs.New(
		filename+".%Y%m%d", // 没有使用go风格反人类的format格式
		//rotatelogs.WithLinkName(filename),
		rotatelogs.WithMaxAge(time.Hour*24*2),
	)

	if err != nil {
		panic(err)
	}
	return hook
}

func SendLog(title string,info interface{},level string)  {
	_, file, line, _ := runtime.Caller(2)
	ZapLogger.Info(file,zap.String(strconv.Itoa(line),common.LOG_DEBUG))
	log,_ :=json.Marshal(info)
	if level == "debug"{
		ZapLogger.Debug(title,zap.String(title,string(log)))
	}else if level == "error"{
		ZapLogger.Error(title,zap.String(title,string(log)))
	}
}